import { store } from '@/redux';
import { JSX } from 'react';
import { Navigate, useLocation } from 'react-router-dom';

// 路由守卫组件
const AuthRouter = (props: { children: JSX.Element }) => {
  // 获取路由信息
  const { pathname } = useLocation();

  //判断是否有token
  const token = store.getState().global.token;
  // 如果没有token，跳转到登录页面
  if (!token) {
    if (pathname !== '/login') {
      return <Navigate to='/login' replace />;
    } else {
      return props.children;
    }
  }

  if (pathname === '/login') {
    // 跳转到系统中
    return <Navigate to='/loading' replace />;
  }

  // 获取权限路由
  const dynmaicRouter = store.getState().auth.authRouter;
  const staticRouter = ['/loading', '/403', "/404"];
  const routerList = [...dynmaicRouter, ...staticRouter];
  if (!routerList.includes(pathname)) {
    // 如果没有权限，跳转到403
    return <Navigate to='/403' replace />;
  }

  return props.children;
};

export default AuthRouter;
